// 创建用户相关的小仓库
import { defineStore } from "pinia";
import { ref } from "vue";
import { reqUserLogin, reqUserInfo, reqUserLogout } from "@/api/user";
import type { LoginForm, LoginResData, userInfoResData } from "@/api/user/type";
import { constantRoutes } from "@/router/routes";
// import { asyncRoutes, anyRoute } from "@/router/routes";
import type { RouteRecordRaw } from "vue-router";
// import router from "@/router";

// 对外暴露仓库
export const useUserStore = defineStore('userStore',
    () => {
        // 用户唯一标识（token）
        let token = ref<string>('');
        // 用户姓名
        let username = ref<string>('');
        // 用户头像
        let avatar = ref<string>('');
        // 按钮权限
        let authButtons = ref<string[]>(['role.button.edit', 'role.button.add']);

        // 仓库存储生成菜单需要的数据（路由）
        let menuRoutes = ref<RouteRecordRaw[]>([]);
        menuRoutes.value = constantRoutes;

        // 用户登录方法
        const getLoginInfo = async (data: LoginForm) => {
            let result: LoginResData = await reqUserLogin(data);
            console.log("登录响应结果是", result);
            if (result.code === 200) {
                token.value = (result.data as string);
                return 'ok';
            }
            return Promise.reject(new Error(result.data));
        }
        // 路由匹配方法
        const filterRoutes = (asyncRoutes: RouteRecordRaw[], routes: string[]) => {
            return asyncRoutes.filter((item: RouteRecordRaw) => {
                if (routes.includes(item.name as string)) {
                    if (item.children && item.children.length > 0) {
                        item.children = filterRoutes(item.children, routes);
                    }
                    return true;
                }
            })
        }
        // 获取用户信息方法
        const getUserInfo = async () => {
            let result: userInfoResData<string> = await reqUserInfo();
            console.log("请求用户信息的结果", result);
            username.value = '张三';
            // if (result.code === 200) {
            //     username.value = (result.data?.name as string);
            //     avatar.value = (result.data?.avatar as string);
            //     authButtons.value = result.data?.buttons;
            //     if (result.data?.routes.length > 0) {
            //         // 调用方法，得到用户有权访问的异步路由
            //         let authRoutes = filterRoutes(JSON.parse(JSON.stringify(asyncRoutes)), result.data?.routes);
            //         // 合并路由，得到用户有权访问的所有菜单路由
            //         menuRoutes.value = [...constantRoutes, ...authRoutes, ...anyRoute];
            //         // 将路由信息添加到router中
            //         [...authRoutes, ...anyRoute].forEach((item: RouteRecordRaw) => {
            //             router.addRoute(item);
            //         })
            //     }
            //     return 'ok';
            // }
            // return Promise.reject(new Error(result.message));
        };
        // 用户退出登录方法
        const userLogout = async () => {
            let result: any = await reqUserLogout();
            if (result.code === 200) {
                token.value = '';
                username.value = '';
                avatar.value = '';
                return 'ok';
            }
            return Promise.reject(new Error(result.message));
        }

        return {
            token,
            menuRoutes,
            getLoginInfo,
            getUserInfo,
            username,
            avatar,
            userLogout,
            authButtons
        }
    },
    {
        persist: {
            // 指定持久化存储的key 和 持久化存储的数据
            key: 'TOKEN',
            pick: ['token']
        }
    }
);